/**
 * 实现生成一个可以读写操作的规则页面
 *
 * @param operate_status 判断当前操作是写还是编辑或者是读操作 值分别为add,modify,view
 * @method  _init:初始化操作
 * @method  _generateRuleTable:生成规则表 默认生成规则表01 后面的规则表02,03都是基于规则表01复制出来的
 * @method  _load:当操作是编辑或者读时从后台加载数据渲染
 * @method  _renderDetailsRule:渲染每个规则表中的细规则
 * @method  _renderRule:作用1.去调用渲染每个规则表中的细规则2.克隆规则表
 * @method  _disabledFormInput:当操作是编辑或者读时，使整个页面处于disabled状态
 * @method  _getSelecteOption：从后台加载数据过来选中对应下拉框中的option
 * @method  _renderSelectDictionaryItem：关联内容下拉数据项添加
 * @method  _dictionarySenceQuery：关联业务板块下拉数据项添加
 * @method  _initDatePicker：初始化时间生成器
 * @method  _addZero：小于10的就添加0
 * @method  _getRuleTableTitle,_sortRuleGroupTable：为规则列表添加列表顺序
 * @method  _btnRuleBind：规则列表按钮点击事件
 * @method  _btnDetailsRuleBind：规则细则按钮点击事件
 * @method  _getParamsFromSelect：表单提交获取下拉框选中的值
 * @method  _getParamsFromTextarea：表单提交获取文本域选中的值
 * @method  _getParamsFromRuleGroupTable：表单提交获取规则表，规则细则的值
 * @method  _getFormParams：表单提交获取表单的值
 * 目前条件无法完成的：获取URL中pruleId的值；当前操作状态；关联政策由于跨系统所以后台目前无法给出准确接口
 */
var _PROTOTYPE_ = {
    _init: function () {
        var _this = this;
        /*this.operate_status = "edit";*/
        this.operate_status = this._getLocationSearch().operate;
        this.loadSencePolicyEftItemDoned = false;
        this.$headerSection = $(".header-section");
        this.$selectPolicyRelation = $(".select-policy-relation");
        this.$selectPolicyStatus = $(".select-policy-status");
        this.$effectTime = $(".effect-time");
        this.$textAreaWarnContent = $(".textarea-warn-content");
        this.$textAreaWarnRemark = $(".textarea-warn-remark");
        this.$ruleSection = $(".rule-section");
        this.$ruleBizScene = $(".rule-bizScene");
        this.$selectSence = this.$ruleBizScene.find(".select-sence");
        this.$groupTableTemplate = $(".rule-groupTable-template");
        switch(this.operate_status){
            case "add":
                this.$headerSection.text("政策提醒新增");
                break;
            case "modify":
                this.$headerSection.text("政策提醒编辑");
                break;
            case "view":
                this.$headerSection.text("政策提醒查看");
                break;
        }
        /*this._dictionarySenceQuery();
         this._getPolicyData();*/
        /*this._dictionaryRuleEftItemQuery();*/
        $.when(this._dictionarySenceQuery(), this._getPolicyData()).done(function () {
            console.log("进入成功");
            _this.loadSencePolicyEftItemDoned =
            true;
            _this._dictionaryRuleEftItemQuery();
        }).fail(function () {
            console.log("进入失败");
            _this.loadSencePolicyEftItemDoned =
            false;
            layer.alert("业务场景,关联政策有一个加载出错了");
        });
        this._initDatePicker();
    },
    _getLocationSearch: function () {
        var obj = {};
        var search = window.location.search.substr(1).split("&");
        for (var i = 0; i < search.length; i++) {
            var tempArr = search[i].split("=");
            obj[tempArr[0]] = tempArr[1];
        }
        return obj;
    },
    _generateRuleTable: function () {
        var $clone = this.$groupTableTemplate.clone().removeClass("rule-groupTable-template");
        this.$ruleSection.append($clone);
        $clone.find(".btn-special").hide();
        this.$selectRuleEftItem = $clone.find(".select-rule-eft-item");
        this._renderSelectDictionaryItem(this.$selectRuleEftItem);
        this.$ruleTrTemplate = $clone.find(".rule-tr-template");
        this.$btnDetailsRule = this.$ruleTrTemplate.find(".btn-rule");
        this.$btnRule = $clone.find("thead .btn-rule");
        this._btnRuleBind();
        this._btnDetailsRuleBind();
        if (this.operate_status == "modify" || this.operate_status == "view") {
            if (this.loadSencePolicyEftItemDoned) {
                this._load();
            }

        }
    },
    _load: function () {
        var _this = this;
        $.ajax({
                   /*url: '../assets/js/testData/policyData.js',*/
                   url: '/policyRules/manage/policyData',
                   type: 'get',
                   data: {"pruleId": this._getLocationSearch().pruleId},
                   /*data: {"pruleId": "rule_20170810032829923063"},*/
                   dataType: 'json',
                   success: function (data) {
                       console.log(data);
                       /*console.log("执行顺序为1");*/
                       if (data.error_code == 0) {
                           _this.result = data.content;
                           _this._getSelecteOption(_this.$selectPolicyRelation, _this.result,
                                                   "policyCode");
                           _this._getSelecteOption(_this.$selectPolicyStatus, _this.result,
                                                   "status");
                           _this._getSelecteOption(_this.$selectSence, _this.result, "bizSceneId");
                           for (var i = 0; i < _this.result.length; i++) {
                               $(".form-horizontal").append("<input type='hidden' class='policy-rule-id' value='"
                                                            + _this.result[i].pruleId + "'/>");
                               _this.$effectTime.val(_this.result[i].eftTimeBegin);
                               _this.$textAreaWarnContent.val(_this.result[i].noticeMsg);
                               _this.$textAreaWarnRemark.val(_this.result[i].remark);
                               _this.resultRuleGroups = _this.result[i].ruleGroups;
                           }
                           _this._renderRule();
                           $(".relation-desc").focus(function(){
                               var val = $(this).parent().prev().find("option:selected").val();
                               if(val=='EQ'||val=='NE'||val=="LT"||val=="GT"){
                                   $(this).val("").attr("data-type","float");
                               }else{
                                   $(this).val("").removeAttr("data-type");
                               }
                           });
                           _this._disabledFormInput();
                           /*_this._renderDetailsRule();*/
                       } else {
                           alert("系统内部错误");
                       }
                   },
                   error: function (a, b, c) {
                       console.log(b);
                   }
               });
    },
    _renderDetailsRule: function (arg) {
        this.$ruleGroupTable = $(".rule-groupTable:not(.rule-groupTable-template)").eq(arg / 2);
        this._getSelecteOption(this.$ruleGroupTable.find(".select-rule-eft-item"),
                               [this.resultRuleDetails[0]], "itemId");
        this._getSelecteOption(this.$ruleGroupTable.find(".select-expression-relation"),
                               [this.resultRuleDetails[0]], "matchType");
        this.$ruleGroupTable.find(".relation-desc").val(this.resultRuleDetails[0].matchVal);
        this.$ruleGroupTable.find(".rule-tr-template").append("<input type='hidden' class='details-rule-id' value='"
                                                              + this.resultRuleDetails[0].ruleId
                                                              + "'/>");
        for (var i = 0; i < this.resultRuleDetails.length; i = i + 2) {
            /*if(this.resultRuleDetails.length>1){*/
            if (this.resultRuleDetails[i + 1]) {
                /*this.$ruleGroupTable.find("tbody").find("tr").first().find(".btn-add").triggerHandler("click",[this.resultRuleDetails[i+2],this.resultRuleDetails[i+1]]);*/
                this.$ruleGroupTable.find("tbody").find(".rule-tr-template").eq(i
                                                                                / 2).find(".btn-add").triggerHandler("click",
                                                                                                                     [this.resultRuleDetails[i
                                                                                                                                             + 2],
                                                                                                                      this.resultRuleDetails[i
                                                                                                                                             + 1]]);
            }
        }
    },
    _renderRule: function () {
        for (var i = 0; i < this.resultRuleGroups.length; i++) {
            if (this.resultRuleGroups[i] != "OR" && this.resultRuleGroups[i] != "AND") {
                this.resultRuleDetails = this.resultRuleGroups[i];
                this._renderDetailsRule(i);
            } else {
                $(".rule-groupTable:not(.rule-groupTable-template)").eq((i - 1)
                                                                        / 2).find("thead .btn-add").triggerHandler("click",
                                                                                                                   this.resultRuleGroups[i]);
            }

        }

    },
    _disabledFormInput: function () {
        if (this.operate_status == "view") {
            $(".form-horizontal").find(":input").attr("disabled",
                                                      "disabled").addClass("disabled-style").end().find(".btn-back").removeAttr("disabled").removeClass("disabled-style");
        }
    },
    _getSelecteOption: function (target, data, prop) {
        var _this = this;
        for (var i = 0; i < data.length; i++) {
            target.find("option").each(function (n, m) {
                if ($(this).val() == data[i][prop]) {
                    $(this).get(0).selected = true;
                    return false;
                }
            });
        }
    },
    _renderSelectDictionaryItem: function (target) {
        if (this.dictionaryRuleEftItemQueryResult.error_code == 0) {
            for (var i = 0; i < this.dictionaryRuleEftItemQueryResult.content.length; i++) {
                var optionHtml = "<option value='"
                                 + this.dictionaryRuleEftItemQueryResult.content[i].dtId + "'>"
                                 + this.dictionaryRuleEftItemQueryResult.content[i].dtValue
                                 + "</option>";
                target.append(optionHtml);
            }
        } else {
            alert("系统内部错误");
        }
    },
    _getPolicyData: function () {
        var _this = this;
        var dtd = $.Deferred();
        $.ajax({
                   /*url: 'http://192.168.0.194:8083/a/jsonp/dropdownList.html',*/
                   url: 'http://219.130.222.62:9004/yxt/a/jsonp/dropdownList.html',
                   type: 'get',
                   dataType: 'jsonp',
                   success: function (data) {
                       console.log(data);
                       /*console.log("执行顺序为2");*/
                       if (data.result) {
                           var result = data.data;
                           if (result.length) {
                               for (var i = 0; i < result.length; i++) {
                                   var optionHtml = "<option value='" + result[i].id + "'>"
                                                    + result[i].title + "</option>";
                                   _this.$selectPolicyRelation.append(optionHtml);
                               }
                           }
                           dtd.resolve();
                       } else {
                           layer.alert("后台执行错误");
                       }
                   },
                   error: function (a, b, c) {
                       console.log(b);
                   }
               });
        return dtd.promise();
    },
    _dictionarySenceQuery: function () {
        var _this = this;
        var dtd = $.Deferred();
        $.ajax({
                   /*url: '../assets/js/testData/sence.js',*/
                   url: '/api/dictionary/search',
                   type: 'get',
                   data: {"dtGroupCode": "biz_sence"},
                   dataType: 'json',
                   success: function (data) {
                       console.log(data);
                       /*console.log("查询业务场景");*/
                       var result = data.content;
                       if (data.error_code == 0) {
                           for (var i = 0; i < result.length; i++) {
                               var optionHtml = "<option value='" + result[i].dtId + "'>"
                                                + result[i].dtValue + "</option>";
                               _this.$selectSence.append(optionHtml);
                           }
                           dtd.resolve();
                       } else {
                           alert("系统内部错误");
                       }
                   },
                   error: function (a, b, c) {
                       console.log(b);
                   }
               });
        return dtd.promise();
    },
    _dictionaryRuleEftItemQuery: function () {
        var _this = this;
        $.ajax({
                   /*url: '../assets/js/testData/ruleEftItem.js',*/
                   url: '/api/dictionary/search',
                   type: 'get',
                   data: {"dtGroupCode": "rule_eft_item"},
                   dataType: 'json',
                   success: function (data) {
                       console.log(data);
                       _this.dictionaryRuleEftItemQueryResult = data;
                       _this._generateRuleTable();
                   },
                   error: function (a, b, c) {
                       console.log(b);
                   }
               });
    },
    _initDatePicker: function () {
        this.$effectTime.datepicker({
                                        dateFormat: "yy-mm-dd"
                                    });
    },
    _addZero: function (num) {
        return num < 10 ? "0" + num : num;
    },
    _getRuleTableTitle: function (target) {
        var txt = target.find("thead").find(".label-name").text();
        return txt.substring(0, 4);
    },
    _sortRuleGroupTable: function () {
        var _this = this;
        $(".rule-groupTable:not(.rule-groupTable-template)").each(function (i, n) {
            var txt = _this._getRuleTableTitle($(this));
            $(this).find("thead").find(".label-name").text(txt + _this._addZero(i + 1));
        });
    },
    _btnRuleBind: function () {
        var _this = this;
        this.btnRuleClick = 0;
        this.$btnRule.on("click", function (event, a) {
            if ($(this).hasClass("btn-add")) {
                /*this.btnRuleClick++;*/
                var $clone = $(this).parents(".rule-groupTable").clone(true);
                var name = "expression-radio" + _this.btnRuleClick++;
                var htmlStr = "<div class=\"tables-relations\">" +
                              "<div class=\"rule-relation-expression rule-relation-expression-sm\">"
                              +
                              "<div class=\"or-expression\"><input type=\"radio\" name='" + name
                              + "' value=\"OR\"/>或</div>" +
                              "<div class=\"and-expression\"><input type=\"radio\" name='" + name
                              + "' value=\"AND\"/>与</div>" +
                              "<div class=\"clean\"></div>" +
                              "</div>" +
                              "</div>";
                $clone.find("thead .btn-special").show();
                if ($clone.find("tbody").find("tr").length > 1) {
                    $clone.find("tbody").find("tr:gt(0)").remove().end().find(".relation-desc").val("");
                } else {
                    $clone.find("tbody").find("tr").find(".relation-desc").val("");
                }
                /*if($(this).parents(".rule-groupTable").next(".tables-relations").length){
                 $(this).parents(".rule-groupTable").next(".tables-relations").after(htmlStr).after($clone);
                 }else{
                 $(this).parents(".rule-groupTable").after($clone).after(htmlStr);
                 }*/
                if (_this.operate_status == "modify") {
                    $clone.find("input[type=hidden]").val("");
                }
                $(this).parents(".rule-groupTable").after($clone).after(htmlStr);
                if ((_this.operate_status == "modify" || _this.operate_status == "view") && a) {
                    /*console.log(a);*/
                    $clone.prev().find("input:radio").each(function () {
                        if ($(this).val() == a) {
                            $(this).get(0).checked = true;
                            return false;
                        } else {
                            $(this).get(0).checked = false;
                        }
                    });
                    $clone.find("input[type=hidden]").remove();
                }
            } else {
                $(this).parents(".rule-groupTable").prev().remove().end().remove();
            }
            _this._sortRuleGroupTable();
        });
    },
    _detailsRuleRadioNamed: function (target) {
        var index = target.parents(".rule-groupTable").index();
        target.parents(".rule-groupTable").find(".tr-relation-expression").each(function (i, n) {
            $(this).find("input:radio").attr("name", "expression-radio" + index + i);
        });
    },
    _btnDetailsRuleBind: function () {
        var _this = this;
        this.$btnDetailsRule.on("click", function (event, a, b) {
            if ($(this).hasClass("btn-add")) {
                var $clone = $(this).parents(".rule-tr-template").clone(true);
                $clone.find(".relation-desc").val("");
                $clone.find(".btn-special").show();
                var htmlStr = "<tr class=\"tr-relation-expression\">" +
                              "<td class=\"label-name\">&nbsp;</td>" +
                              "<td class=\"label-content\">" +
                              "<div class=\"rule-relation-expression\">" +
                              "<div class=\"or-expression\"><input type=\"radio\" name=\"expression-radio\" value=\"OR\"/>或</div>"
                              +
                              "<div class=\"and-expression\"><input type=\"radio\" name=\"expression-radio\" value=\"AND\"/>与</div>"
                              +
                              "<div class=\"clean\"></div>" +
                              "</div>" +
                              "</td>" +
                              "<td class=\"label-relation\">&nbsp;</td>" +
                              "<td class=\"label-relationDesc\">&nbsp;</td>" +
                              "<td>&nbsp;</td>" +
                              "</tr>";
                /*if($(this).parents(".rule-tr-template").next(".tr-relation-expression").length){
                 $(this).parents(".rule-tr-template").next(".tr-relation-expression").after(htmlStr).after($clone);
                 }else{
                 $(this).parents(".rule-tr-template").after($clone).after(htmlStr);
                 }*/
                $(this).parents(".rule-tr-template").after($clone).after(htmlStr);
                _this._detailsRuleRadioNamed($(this).parents(".rule-tr-template"));
                if ((_this.operate_status == "modify" || _this.operate_status == "view") && a
                    && b) {
                    /*console.log(a);
                     console.log(b);*/
                    var dataArr = [];
                    dataArr.push(a);
                    _this._getSelecteOption($clone.find(".select-rule-eft-item"), dataArr,
                                            "itemId");
                    _this._getSelecteOption($clone.find(".select-expression-relation"), dataArr,
                                            "matchType");
                    $clone.find(".relation-desc").val(a.matchVal);
                    $clone.prev().find("input:radio").each(function () {
                        if ($(this).val() == b) {
                            $(this).get(0).checked = true;
                            return false;
                        } else {
                            $(this).get(0).checked = false;
                        }
                    });
                    $clone.find("input[type=hidden]").remove();
                    $clone.append("<input type='hidden' class='details-rule-id' value='" + a.ruleId
                                  + "'/>");
                }

            } else {
                $(this).parents(".rule-tr-template").prev().remove().end().remove();
            }
        });
    },
    _getParamsFromSelect: function (target) {
        return target.find("option:selected").val();
    },
    _getParamsFromTextarea: function (target) {
        return target.val();
    },
    _getParamsFromRuleGroupTable: function () {
        var _this = this;
        var ruleGroupsArr = [];
        $(".rule-groupTable:not(.rule-groupTable-template)").each(function (i, n) {
            var ruleGroupObj = [];
            $(this).find(".rule-tr-template").each(function (j, k) {
                var detailsRuleObj = {};
                detailsRuleObj.itemId =
                _this._getParamsFromSelect($(this).find(".select-rule-eft-item"));
                detailsRuleObj.matchType =
                _this._getParamsFromSelect($(this).find(".select-expression-relation"));
                detailsRuleObj.matchVal = $(this).find(".relation-desc").val();
                if (this.operate_status != "add") {
                    detailsRuleObj.ruleId = $(this).find(".details-rule-id").val();
                }
                ruleGroupObj.push(detailsRuleObj);
                if ($(this).next(".tr-relation-expression").length) {
                    ruleGroupObj.push($(this).next(".tr-relation-expression").find("input:radio:checked").val());
                }
            });
            ruleGroupsArr.push(ruleGroupObj);
            if ($(this).next(".tables-relations").length) {
                ruleGroupsArr.push($(this).next(".tables-relations").find("input:radio:checked").val());
            }
            /*ruleGroupObj.push(ruleGroupObj);*/
        });
        return ruleGroupsArr;
    },
    _getFormParams: function () {
        var obj = {};
        obj.policyCode = this._getParamsFromSelect(this.$selectPolicyRelation);
        obj.status = this._getParamsFromSelect(this.$selectPolicyStatus);
        obj.bizSceneId = this._getParamsFromSelect(this.$selectSence);
        obj.eftTimeBegin = this.$effectTime.val();
        obj.noticeMsg = this._getParamsFromTextarea(this.$textAreaWarnContent);
        obj.remark = this._getParamsFromTextarea(this.$textAreaWarnRemark);
        if (this.operate_status != "add") {
            obj.pruleId = $(".form-horizontal").find(".policy-rule-id").val();
        }
        obj.ruleGroups = this._getParamsFromRuleGroupTable();
        return obj;
    }
}
